package com.yearEndWorkload.handler.excelHandler;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.List;


/**
 * 与SpecialWorkSheetWriteHandler长得一摸一样，但是为了扩展型，将这两个分开写。
 * */
@Slf4j
public class NewOutstandingSheetWriteHandler  implements SheetWriteHandler {
    private List<String> selectList;

    public void selectList(List<String> selectList) {
        this.selectList = selectList;
    }


    @Override
    public void afterSheetCreate(SheetWriteHandlerContext context) {
        log.info("第{}个Sheet写入成功。", context.getWriteSheetHolder().getSheetNo());

        setMultiLevelDataValidation(context);

    }

    private void setMultiLevelDataValidation(SheetWriteHandlerContext context) {

        // 将 this.selectList 写入第11列并隐藏
        Sheet sheet = context.getWriteSheetHolder().getSheet();
        int rowIndex = 1; // 开始写入数据的行索引
        for (String service : this.selectList) {
            Row row = sheet.getRow(rowIndex);
            if (row == null) {
                row = sheet.createRow(rowIndex);
            }
            Cell cell = row.createCell(10); // 创建第八列单元格
            cell.setCellValue(service); // 设置单元格值
            sheet.setColumnHidden(10, true); // 隐藏第八列
            rowIndex++;
        }

        // 设置下拉列表
        CellRangeAddressList performanceTypeRange = new CellRangeAddressList(1, SpreadsheetVersion.EXCEL2007.getLastRowIndex(), 2, 2); // 第三列作为下拉选项
        DataValidationHelper helper = context.getWriteSheetHolder().getSheet().getDataValidationHelper();
        DataValidationConstraint constraint = helper.createFormulaListConstraint("K:K"); // 指向第11列作为数据源
        DataValidation validation = helper.createValidation(constraint, performanceTypeRange);
        validation.setShowErrorBox(true); // 显示错误提示框
        context.getWriteSheetHolder().getSheet().addValidationData(validation);

    }
}
